﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;
using Microsoft.Win32;
using NetFwTypeLib;
using System.Security.Principal;
using System.Security.Permissions;

namespace readnumber
{
    public delegate void MyEventHandler(object sender);

    public partial class Form1 : Form
    {
        network myNetwork;
        RegistryKey rkApp;
        public bool bMinimize = false;

        delegate void SetTextCallback(string text);
        delegate void SetImageCallback();
        
        public void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.textBox1.Text = text;
            }
        }

        public void imageTransmitted()
        {
            if (this.textBox1.InvokeRequired)
            {
                SetImageCallback d = new SetImageCallback(imageTransmitted);
                this.Invoke(d);
            }
            else
            {
                FileStream fileImage = File.Open("image.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                Bitmap biTemp = (Bitmap)Bitmap.FromStream(fileImage);
                //Image imTemp = Image.FromStream(fileImage);
                fileImage.Close();

                //biTemp = AdjustContrast(biTemp, 1.0f);
                
                this.pictureBox1.Image = biTemp;
                openFileDialog1.FileName = "image.jpg";
                button3_Click(this, null);
                webBrowser1.Visible = false;
            }
        }

        public Form1()
        {
            InitializeComponent();

            // ADD FIREWALL EXCEPTION
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
            INetFwRule firewallRuleX;
            try
            {
                firewallRuleX = firewallPolicy.Rules.Item("ReadNumber");
            }
            catch
            {
                firewallRuleX = null;
            }
            if (firewallRuleX == null ||firewallRuleX.Enabled == false || firewallRuleX.ApplicationName != Application.ExecutablePath)
            {
                WindowsIdentity curIdentity = WindowsIdentity.GetCurrent();
                WindowsPrincipal myPrincipal = new WindowsPrincipal(curIdentity);
                bool isAdmin = myPrincipal.IsInRole(WindowsBuiltInRole.Administrator);

                if (isAdmin)
                {
                    INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                    firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
                    firewallRule.Description = "Allow Readnumber to be found in the network";
                    firewallRule.ApplicationName = Application.ExecutablePath;
                    firewallRule.Enabled = true;
                    firewallRule.InterfaceTypes = "All";
                    firewallRule.Name = "ReadNumber";

                    firewallPolicy.Rules.Add(firewallRule);
                }
                else
                {
                    if (MessageBox.Show("Warning, this application is not present in your firewall, maybe your firewall will block this app. Do you want add this app to your firewall?", "Firewall exception", MessageBoxButtons.YesNoCancel) == System.Windows.Forms.DialogResult.Yes)
                    {
                        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                        startInfo.UseShellExecute = true;
                        startInfo.WorkingDirectory = Environment.CurrentDirectory;
                        startInfo.FileName = Application.ExecutablePath;
                        startInfo.Verb = "runas";
                        try
                        {
                            this.Enabled = false;
                            this.Close();
                            Application.Exit();
                            System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(startInfo);
                            return;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return; //If cancelled, do nothing
                        }
                    }
                }
            }
            // ADD FIREWALL EXCEPTION

            rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            if (rkApp.GetValue("ReadNumber_NokiaApp") == null)
            {
                autostartOnWindowsStartupToolStripMenuItem.Checked = false;
            }
            else
            {
                autostartOnWindowsStartupToolStripMenuItem.Checked = true;
            }
            
            myNetwork = new network();

            myNetwork.createConnection(7186, this);

            foreach (String sIP in myNetwork.getIP())
            {
                ((ToolStripComboBox)menuStrip1.Items[2]).Items.Add(sIP + ":7186");
            }
            if (((ToolStripComboBox)menuStrip1.Items[2]).Items.Count == 3) ((ToolStripComboBox)menuStrip1.Items[2]).SelectedIndex = 1;
            else ((ToolStripComboBox)menuStrip1.Items[2]).SelectedIndex = 0;
            //menuStrip1.Items[1].Text = myNetwork.getIP() + ":7186";
        }
        
        private void button2_Click(object sender, EventArgs e)
        {
            myNetwork.closeConnection();
            this.Close();
            Application.Exit();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();

            if (openFileDialog1.FileName.EndsWith(".jpg") || openFileDialog1.FileName.EndsWith(".png"))
            {
                pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
            }

            webBrowser1.Visible = false;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            button5.Visible = true;
            button3.Visible = false;
            Application.DoEvents();

            textBox1.Text = "loading text";
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("tesseract.exe", openFileDialog1.FileName + " temp " + toolStripTextBox1.Text);
            psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);
            p.WaitForExit(5000);

            System.IO.FileStream fs;
            byte[] buffer = new byte[1024];
            int iRead;
            System.Text.Encoding enc = System.Text.Encoding.ASCII;

            textBox1.Text = "";
            fs = System.IO.File.Open("temp.txt", System.IO.FileMode.Open);
            do
            {
                iRead = fs.Read(buffer, 0, 1024);
                textBox1.Text += enc.GetString(buffer);
                for (int k = 0; k < 10; k++)
                    textBox1.Text = textBox1.Text.Replace("??", "?");
                for (int k = 0; k < 10; k++)
                    textBox1.Text = textBox1.Text.Replace("\\\\", "\\");
                textBox1.Text = textBox1.Text.Replace("\n", " ");
                if (textBox1.Text.Length < 128)
                {
                    SendKeys.Send(textBox1.Text);
                }
            } while (iRead == 1024);
            fs.Close();
            Application.DoEvents();
            button3.Visible = true;
            button5.Visible = false;
        }

        private void testToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            myNetwork.closeConnection();
            Application.Exit();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized; 
        }
        
        private void Form1_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == this.WindowState)
            {
                notifyIcon1.Visible = true;
                notifyIcon1.BalloonTipText = "Shoot a foto with your nokia";
                notifyIcon1.ShowBalloonTip(500);
                this.Hide();
                this.ShowInTaskbar = false;
            }
            else if (FormWindowState.Normal == this.WindowState)
            {
                timer1.Start();
                //notifyIcon1.Visible = false;
                this.ShowInTaskbar = true;
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            toolStripMenuItem1_Click(sender, e);
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y); 
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Show();
            Application.DoEvents();
            this.WindowState = FormWindowState.Normal;
            this.TopMost = true;

            Application.DoEvents();
            this.ShowInTaskbar = true;

            Application.DoEvents();
            this.Focus();
            this.TopMost = false;

            timer1.Start();            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Stop();
            timer1.Enabled = false;
            notifyIcon1.Visible = false;
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (bMinimize)
            {
                notifyIcon1.Visible = true;
                this.ShowInTaskbar = false;
                this.Hide();
            }
        }

        private void autostartOnWindowsStartupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (autostartOnWindowsStartupToolStripMenuItem.Checked)
            {
                rkApp.SetValue("ReadNumber_NokiaApp", Application.ExecutablePath.ToString() + " -m");
            }
            else
            {
                rkApp.DeleteValue("ReadNumber_NokiaApp", false);
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBox1.Text = "App to insert numbers parsed from Nokia-cams.\r\n\r\nVersion 1.0\r\n\r\n© 2012 - Adriano";
        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            webBrowser1.Visible = true;
        }

        private void infoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            aboutToolStripMenuItem_Click(sender, e);
            MessageBox.Show(textBox1.Text, "ReadNumber");
        }

        private void tesseractOCRToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://code.google.com/p/tesseract-ocr/wiki/FAQ");
        }
    }

}
